<template>
  <el-dialog
      :visible.sync="show"
      :title="title"
       width="80%"
       top="2vh"
       append-to-body
       :close-on-click-modal="false"
      :before-close="close">
    <div style="margin-bottom:10px;">
      <el-steps simple :active="active" finish-status="success">
      <el-step title="新建基本信息">
      </el-step>
      <el-step title="填写合同文件"></el-step>
    </el-steps>
    </div>
    <div v-if="active==0" style="overflow:auto;max-height:300px;">
      <el-form :model="contractInfo" label-width="130px" ref="contractRef" :rules="rules">
          <el-row>
            <el-col :span="12">
               <el-form-item  prop="contractName">
                 <template slot="label">
                      <span>合同名称</span>
                      <el-tooltip content="名称做为发起合同签署流程的场景名称" placement="top">
                        <i class="el-icon-info"></i>
                      </el-tooltip>
                  </template>
                 <el-input class="wp-form-280" v-model.trim="contractInfo.contractName" placeholder="合同名称"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="所属公司" prop="companyCode">
                    <SelectCompany  v-model="contractInfo.companyCode"/>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="销售订单" prop="orderNo">
                <PopoverSearch clearable @hide="salesOrderhide"  :params="{status:3,companyCode:contractInfo.companyCode}" type='salesOrder' placeholder="+添加订单" v-model="contractInfo.orderNo" lableKey="orderNo" valueKey="orderNo"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="客户" prop="customerCode">
                <PopoverSearch  :disabled="!customerCanChange" v-model="contractInfo.customerCode" :name.sync="contractInfo.customerName"/>
             </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同商定日期">
                <el-date-picker style="width:280px" type="date"  value-format="yyyy-MM-dd HH:mm:ss" v-model="contractInfo.contractDealDate" placeholder="合同商定日期"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="负责人" prop="chargePerson">
                    <EmployeeSeach v-model="contractInfo.chargePerson" :employeeName.sync="contractInfo.chargePersonName"/>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
            <el-form-item label="合同签署有效天数" prop="validity">
                <!-- <el-input-number  controls-position="right"  style="width:280px" :min="1" v-model="contractInfo.validity" placeholder="合同签署有效天数"></el-input-number> -->
                <el-input  controls-position="right"  style="width:280px"  v-model.number="contractInfo.validity" placeholder="合同签署有效天数">
                                 <template slot="append">天</template>
                </el-input>
            </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item label="备注" prop="remark">
                        <el-input
                        class="wp-form-280"
                        type="textarea"
                        v-model.trim="contractInfo.remark"
                        placeholder="备注"
                      ></el-input>
                    </el-form-item>
            </el-col>
          </el-row>
        </el-form>
    </div>
    <div  v-if="active==1">
     <el-form :model="contractFileInfo" label-width="120px" ref="contractFileRef">
       <el-row>
         <el-col :span="12">
           <el-form-item label="销售订单">
              <el-input  class="wp-form-280"  readonly v-model="contractFileInfo.orderNo" placeholder="销售订单"></el-input>
           </el-form-item>
         </el-col>
        <el-col :span="12">
           <el-form-item label="客户">
              <el-input  class="wp-form-280"  readonly v-model="contractFileInfo.customerName" placeholder="客户"></el-input>
           </el-form-item>
         </el-col>
       </el-row>
        <el-row>
            <el-col :span="12">
                   <el-form-item label="合同号" prop="contractNo" :rules="[{ required: policy==2, message: '不能为空', trigger: 'blur' }]">
                        <el-radio v-model="policy" label="1" border size="mini">自动生成</el-radio>
                        <el-radio v-model="policy" label="2" border size="mini">手动输入</el-radio>
                        <el-input
                        v-if="policy==2"
                        class="wp-form-280"
                        v-model.trim="contractFileInfo.contractNo"
                        placeholder="输入合同号"
                        clearable
                        ></el-input>
                    </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同文件名称" prop="contractFileName"  :rules="[{ required:true, message: '不能为空', trigger: 'blur' }]">
                <el-input class="wp-form-280" v-model="contractFileInfo.contractFileName" placeholder="合同文件名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同模板" prop="contractTemplate" :rules="[{ required:true, message: '不能为空', trigger: 'blur' }]">
                <el-select clearable style="width:280px" v-model="contractFileInfo.contractTemplate" placeholder="合同模板" @change="selectChange($event)">
                  <el-option v-for="(item,index) in contractTemplateList" :label="item.contractTemplateName" :value="item.contractTemplate" :key="index"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                       <el-input
                        class="wp-form-280"
                        type="textarea"
                        v-model="contractFileInfo.remark"
                        placeholder="备注"
                      ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        <span v-for="(item,index) in contractTemplateFieldList" :key="index" >
            <div v-if="item.fieldType===99">
             <div v-if="item.fieldRules==='1'">
             <div style="text-align: right;margin-bottom:5px;">
               <el-button type="" icon="el-icon-zoom-in" @click.native="toPreviewCombination">查看产品组件明细</el-button>
               <el-button type="warning" icon="el-icon-circle-plus-outline" @click="toAddCombination">配置产品组件</el-button>
             </div>
              <Combination title="配置产品组件"  v-if="visibleCombination" :contractDataInfoList="contractDataInfoList" :list="porductList" :visible.sync="visibleCombination" @save="saveCombination"/>
              <el-table  max-height="150px" :key="combinationKey" border :data="combinationProductList"  :span-method="objectSpanMethod">
                <el-table-column fixed="left"  align="center" label="组件名称" prop="combinationName" show-overflow-tooltip></el-table-column>
                <el-table-column label="产品名称" prop="productName" show-overflow-tooltip></el-table-column>
                <el-table-column label="产品类型" prop="productTypeName" show-overflow-tooltip></el-table-column>
                <el-table-column label="单位" prop="unit"></el-table-column>
                <el-table-column label="产品数量" prop="productNum"></el-table-column>
                <el-table-column label="销售单价（元）" width="120" prop="actualPrice"></el-table-column>
                <el-table-column fixed="right" align="center" label="合计" prop="totalAmount"></el-table-column>
                <el-table-column fixed="right" label="备注"  align="center" prop="combinationRemark" show-overflow-tooltip></el-table-column>
                <el-table-column fixed="right" label="操作">
                  <template slot-scope="scope">
                   <el-button type="danger" size="mini" @click.native="delCombination(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
                <el-table border :data="contractDataInfoList" max-height="190px">
                  <el-table-column label="产品名称" prop="productName" show-overflow-tooltip></el-table-column>
                  <el-table-column label="产品类型" prop="productTypeName" show-overflow-tooltip></el-table-column>
                  <el-table-column label="销售数量" prop="productNum" show-overflow-tooltip></el-table-column>
                  <el-table-column label="单位" prop="unit"></el-table-column>
                  <el-table-column label="销售单价（元）" prop="actualPrice"></el-table-column>
                  <el-table-column label="合计" align="center" prop="discountTotalAmount"></el-table-column>
                </el-table>
            </div>
          </div>
          <div v-else-if="item.fieldType===100" style="text-align:right;">
                <el-button icon="el-icon-zoom-in" v-if='contractDataServiceInfoList && contractDataServiceInfoList.length>0' @click="toPreviewService">查看服务费明细</el-button>
          </div>
          <div v-else style="margin-top:5px;max-height:100px;overflow:auto;">
            <el-form-item   :label="item.fieldName"  :rules="item.isRequired===1?[{ required:true, message: '不能为空', trigger: 'blur' }]:[]">
              <el-input class="wp-form-280" v-if="item.fieldType===0"  v-model.trim="contractDataInfo[item.fieldVariable]" :placeholder="item.fieldName"></el-input>
              <el-input class="wp-form-280" v-else-if="item.fieldType===4"  type="textarea" v-model.trim="contractDataInfo[item.fieldVariable]" :placeholder="item.fieldName"></el-input>
              <el-select style="width:280px" v-else-if="item.fieldType===1"  v-model.trim="contractDataInfo[item.fieldVariable]" :placeholder="item.fieldName">
                  <option v-for="(op,i) in eval('('+item.fieldSourceValue+')')" :key="i" :label="op.lable" :value="op.value"></option>
              </el-select>
              <el-date-picker
                  style="width:280px"
                  v-else-if="item.fieldType===2"  v-model.trim="contractDataInfo[item.fieldVariable]" :placeholder="item.fieldName"
                  :format="item.fieldRules" :value-format="item.fieldRules"
              ></el-date-picker>
              <el-input class="wp-form-280" v-else-if="item.fieldType===3"  v-model.trim="contractDataInfo[item.fieldVariable]" :placeholder="item.fieldName"></el-input>
            </el-form-item>
          </div>
        </span>
      </el-form>
    </div>
    <ServicePerview  title="服务费明细" :data="contractDataServiceInfoList"  :visible.sync="visibleServicePreview"/>
    <ProductPerview title="产品组件明细"  @delCombination="delCombination"  :data="combinationProductList" :visible.sync="visibleCombinationPreview"/>
    <div style="text-align: center; margin-top:5px">
      <el-button  @click.native="close">取 消</el-button>
      <el-button type="success" @click.native="save">保 存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import PopoverSearch from '@/views/components/popoverSearch'
import SelectCompany from '@/views/system/components/company'
import EmployeeSeach from '@/views/components/EmployeeSeach'
import Combination from '@/views/eims/components/combination'
import ProductPerview from '@/views/eims/components/combination/ProductPreview'
import ServicePerview from '@/views/eims/components/combination/ServicePerview'
import salesOrder from '@/api/eims/sales/salesOrderAPI'
import contract from '@/api/eims/contract'
export default {
  props: {
    visible: Boolean,
    title: String,
    data: Object,
    customerCanChange: {type: Boolean, default: false}
  },
  components: {PopoverSearch, EmployeeSeach, SelectCompany, Combination, ServicePerview, ProductPerview},
  watch: {
    visible: {
      handler (val) {
        this.show = val
      },
      immediate: true
    },
    data: {
      handler (val) {
        if (val) {
          this.contractInfo = {...val}
          this.active = val && val.contractCode ? 1 : 0
        }
      },
      deep: true,
      immediate: true
    },
    active: {
      handler (val, old) {
        if ((old === 0 || old === undefined) && val === 1) {
          this.contractFileInfo.contractCode = this.contractInfo.contractCode
          this.contractFileInfo.orderNo = this.contractInfo.orderNo
          this.contractFileInfo.customerCode = this.contractInfo.customerCode
          this.contractFileInfo.customerName = this.contractInfo.customerName
          this.getContractTemplateList()
        }
      },
      immediate: true
    },
    show (val) {
      this.$emit('update:visible', val)
    }
  },
  data () {
    return {
      show: false,
      visibleCombination: false,
      visibleCombinationPreview: false,
      visibleServicePreview: false,
      pos: 0,
      active: 0,
      policy: '1',
      combinationKey: 1,
      contractInfo: {},
      contractFileInfo: {},
      porductList: [],
      contractTemplateList: [],
      contractTemplateFieldList: [],
      contractProductTemplateField: {},
      contractServiceTemplateField: {},
      contractTemplateFieldRulesList: [],
      spanArr: [],
      contractDataInfo: {},
      contractDataInfoList: [], // 订单产品（组件）
      contractDataServiceInfoList: [], // 订单服务费
      combinationProductList: [], // 产品组件列表
      rules: {
        contractName: [{ required: true, trigger: 'blur', message: '不能为空' }],
        companyCode: [{ required: true, trigger: 'blur', message: '不能为空' }],
        orderNo: [{ required: true, trigger: 'blur', message: '不能为空' }],
        chargePerson: [{ required: true, trigger: 'blur', message: '不能为空' }]
      }
    }
  },
  methods: {
    close () {
      if (this.active === 1) {
        this.$msgBox.confirm('确认不填写合同文件了？', () => {
          this.show = false
        })
      } else {
        this.show = false
      }
    },
    toAddCombination () {
      this.visibleCombination = true
    },
    toPreviewService () {
      this.visibleServicePreview = true
    },
    getSpanArr (data, key) {
      this.spanArr = []
      if (data === null) {
        return
      }
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          if (data[i][key] === data[i - 1][key]) {
            this.spanArr[ this.pos ] += 1// 合并行数
            this.spanArr.push(0)// 新增一个被合并行 0表示要合并
          } else {
            this.spanArr.push(1)// 否则不合并
            this.pos = i// 指向位移
          }
        }
      }
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 6 || columnIndex === 7 || columnIndex === 8) {
        const rowSpan = this.spanArr[rowIndex]
        const colSpan = rowSpan > 0 ? 1 : 0
        return {
          rowspan: rowSpan,
          colspan: colSpan // 相当于给给表格加上rowspan,colspan属性
        }
      }
    },
    salesOrderhide (data) {
      if (data && Object.keys(data).length > 0) {
        this.contractInfo.customerName = data.customerName
        this.contractInfo.customerCode = data.customerCode
      } else {
        this.contractInfo.customerName = null
        this.contractInfo.customerCode = null
      }
    },
    getOrderServiceList (orderNo, orderServiceFiled) {
      salesOrder.getOrderServiceListAPI(orderNo).then(res => {
        this.contractDataServiceInfoList = res.data || []
      })
    },
    getOrderProductList (orderNo, orderFiled) {
      salesOrder.getOrderProductListAPI(orderNo).then(res => {
        this.contractTemplateFieldRulesList = orderFiled.contractTemplateFieldRulesInfoList || []
        if (orderFiled.needDiyCombination === false) {
          this.contractDataInfoList = res.data || []
        } else {
          this.contractDataInfoList = []
          this.porductList = res.data || []
          this.porductList.forEach(item => {
            item.availableNum = item.availableNum || item.productNum
          })
        }
      })
    },
    getContractTemplateList () {
      contract.getContractTemplateListAPI({}).then(res => {
        this.contractTemplateList = res.data.list || []
      })
    },
    selectChange (val) {
      contract.getContractTemplateFieldAPI(val).then(res => {
        if (res.data) {
          this.contractTemplateFieldList = res.data || []
          // 订单产品信息
          const orderFiled = res.data.find(v => v.fieldType === 99)
          if (orderFiled && this.contractFileInfo.orderNo) {
            this.contractProductTemplateField = orderFiled
            this.getOrderProductList(this.contractFileInfo.orderNo, orderFiled)
          }
          // 订单服务信息
          const orderServiceFiled = res.data.find(v => v.fieldType === 100)
          if (orderServiceFiled && this.contractFileInfo.orderNo) {
            this.contractServiceTemplateField = orderServiceFiled
            this.getOrderServiceList(this.contractFileInfo.orderNo, orderServiceFiled)
          }
        }
      })
    },
    delCombination (row) {
      const delIndex = []
      this.$msgBox.confirm('确认删除', () => {
        for (let index = 0; index < this.combinationProductList.length; index++) {
          const element = this.combinationProductList[index]
          if (element.combinationName === row.combinationName) {
            this.jsPorductAvailableNum(element, 1)
            delIndex.push(index)
          }
        }
        if (delIndex.length > 0) {
          this.combinationProductList.splice(delIndex[0], delIndex.length)
        }
        const deIndex = this.contractDataInfoList.findIndex(v => v.combinationName === row.combinationName)
        if (deIndex && deIndex >= 0) {
          this.contractDataInfoList.splice(deIndex, 1)
        }
      })
    },
    saveCombination (data) {
      this.contractDataInfoList.push(data)
      const productList = data.productList
      for (let index = 0; index < productList.length; index++) {
        const element = productList[index]
        this.jsPorductAvailableNum(element, -1)
        const info = {...element}
        info.combinationName = data.combinationName
        info.combinationRemark = data.combinationRemark
        info.totalAmount = data.totalAmount
        this.combinationProductList.unshift(info)
      }
      this.getSpanArr(this.combinationProductList, 'combinationName')
      this.combinationKey = Math.random()
    },
    jsPorductAvailableNum (element, js = -1) {
      this.porductList.forEach(item => {
        if (element.productCode === item.productCode) {
          const v = item.availableNum + (js * element.productNum)
          if (v >= 0) {
            item.availableNum = v
          }
        }
      })
    },
    toPreviewCombination () {
      if (this.combinationProductList && this.combinationProductList.length > 0) {
        this.visibleCombinationPreview = true
      } else {
        this.$msgBox.error('还未配置产品组件')
      }
    },
    save () {
      if (this.active === 0) {
        this.$refs.contractRef.validate(validate => {
          if (validate) {
            contract.saveContractAPI(this.contractInfo).then(res => {
              if (res.code === 0) {
                this.contractInfo.contractCode = res.data
                this.active = 1
              }
            })
          }
        })
      } else if (this.active === 1) {
        if (!this.contractFileInfo.contractCode || this.contractFileInfo.contractCode === '') {
          this.$msgBox('合同编码不存在')
          return
        }
        this.$refs.contractFileRef.validate(validate => {
          if (validate) {
            const param = {...this.contractFileInfo}
            let contractData = null
            if (this.contractDataInfo && Object.keys(this.contractDataInfo).length > 0) {
              contractData = {...this.contractDataInfo}
            }
            if (!this.checkContractTemplateField(this.contractDataInfo, this.contractTemplateFieldList)) {
              return
            }
            // 订单产品信息
            const list = this.filerContractListData(this.contractDataInfoList, this.contractTemplateFieldRulesList)
            if (list && list.length > 0) {
              contractData = contractData !== null ? contractData : {}
              const productListVariable = this.contractProductTemplateField['fieldVariable'] || 'porductList'
              contractData[productListVariable] = list
            } else {
              this.$msgBox.error('合同产品信息为空')
              return
            }
            // 订单服务费信息
            if (this.contractDataServiceInfoList && this.contractDataServiceInfoList.length > 0) {
              contractData = contractData !== null ? contractData : {}
              const serviceListVariable = this.contractServiceTemplateField['fieldVariable'] || 'serviceList'
              contractData[serviceListVariable] = this.filerContractServiceListData(this.contractDataServiceInfoList)
            }
            param.contractData = JSON.stringify(contractData)
            console.log('save param', contractData, param)
            contract.saveContractFileAPI([param]).then(res => {
              if (res.code === 0) {
                this.active = 2
                this.close()
                this.$emit('afterSave', res)
              }
            })
          }
        })
      }
    },
    checkContractTemplateField (contractDataInfo, contractTemplateFieldList) {
      for (let index = 0; index < contractTemplateFieldList.length; index++) {
        const fieldVariable = contractTemplateFieldList[index]['fieldVariable']
        const isRequired = contractTemplateFieldList[index]['isRequired']
        const dataValue = contractDataInfo[fieldVariable]
        if (isRequired === 1 && (!dataValue || dataValue === null || dataValue === '')) {
          const fieldName = contractTemplateFieldList[index]['fieldName'] || ''
          this.$msgBox.error(fieldName + '不能为空')
          return false
        }
      }
      return true
    },
    filerContractServiceListData (list) {
      // 过滤一些字段，保留有用的字段
      return list.map(item => {
        const p = {}
        p.serviceCode = item.serviceCode
        p.serviceName = item.serviceName
        p.actualTotalAmount = item.actualTotalAmount
        p.remark = item.remark
        p.orderNo = item.orderNo
        const salesServiceDetailInfoList = item.salesServiceDetailInfoList
        if (salesServiceDetailInfoList && salesServiceDetailInfoList.length > 0) {
          p.salesServiceDetailInfoList = salesServiceDetailInfoList.map(vv => {
            return {serviceDetailName: vv.serviceDetailName, remark: vv.remark, unit: vv.unit, price: vv.price, totalAmount: vv.totalAmount, serviceNum: vv.serviceNum}
          })
        } else {
          p.salesServiceDetailInfoList = []
        }
        return p
      })
    },
    filerContractListData (list, rules) {
      const fieldRules = this.contractProductTemplateField['fieldRules']
      // 判断是否为自定义模板
      if (rules && rules.length > 0) {
        // 根据规则过滤一些字段，保留有用的字段
        return list.map(v => {
          const p = {}
          for (let index = 0; index < rules.length; index++) {
            const key = rules[index]['fieldRulesContent']
            if (key) {
              p[key] = v[key] || ''
            }
          }
          return p
        })
      } else {
        if (fieldRules && fieldRules === '1') {
          // 自定义组件过滤一些字段，保留有用的字段
          return list.map(v => {
            if (v.productList) {
              v.list = v.productList.map(vv => {
                return {
                  'productName': vv.productName,
                  'productTypeName': vv.productTypeName,
                  'productModel': vv.productModel,
                  'unit': vv.unit,
                  'productNum': vv.productNum,
                  'actualPrice': vv.actualPrice,
                  'discountRate': vv.discountRate,
                  'discountTotalAmount': vv.discountTotalAmount,
                  'remark': vv.remark
                }
              })
              delete v.productList
            }
            return v
          })
        } else {
          return list
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-combination-box{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  border-bottom: 1px solid #f2f2f2;
  margin: 5px 0;
}
</style>
